from model import House  # 使用相对路径导入
from flask import Blueprint, render_template, request, jsonify
from sqlalchemy import func

# 创建蓝图，蓝图的名称为 'index_page'
index_page = Blueprint('index_page', __name__)


@index_page.route('/search/keyword/', methods=['POST'])
def search_kw():
    kw = request.form.get('kw')
    info = request.form.get('info')

    if not kw or not info:
        return jsonify({'code': 0, 'info': '缺少必要参数'})

    if info == '地区搜索':
        print("进入了")
        house_date = House.query.with_entities(
            House.address, func.count()
        ).filter(House.address.contains(kw))
        result = house_date.group_by(House.address).order_by(
            func.count().desc()
        ).limit(9).all()

        if result:
            data = [{'t_name': i[0], 'num': i[1]} for i in result]
            return jsonify({'code': 1, 'info': data})
        else:
            return jsonify({'code': 0, 'info': []})

    if info == '户型搜索':
        house_date = House.query.with_entities(
            House.rooms, func.count()
        ).filter(House.rooms.contains(kw))
        result = house_date.group_by(House.rooms).order_by(
            func.count().desc()
        ).limit(9).all()

        if result:
            data = [{'t-name': i[0], 'num': i[1]} for i in result]
            return jsonify({'code': 1, 'info': data})
        else:
            return jsonify({'code': 0, 'info': []})


@index_page.route('/')
def index():
    # 获取房源总数
    house_total_num = House.query.count()

    # 获取最新发布的房源列表
    house_new_list = House.query.order_by(House.publish_time.desc()).limit(6).all()

    # 获取最热门的房源列表
    house_hot_list = House.query.order_by(House.page_views.desc()).limit(4).all()

    return render_template('index.html',
                           num=house_total_num,
                           house_new_list=house_new_list,
                           house_hot_list=house_hot_list)
